<template>
  <EvDrawer
    :title="title"
    :drawer="dialogVisible"
    size="45%"
    @handleClose="handleDialogClose"
    @handleCancel="handleDialogCancel"
    @handleConfirm="handleDialogConfirm"
    :append-to-body="true"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="auto" size="medium" :validate-on-rule-change="false">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="模型名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入模型名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模型编号" prop="code">
            <el-input v-model="form.code" placeholder="请输入模型编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="模型数据" prop="data">
            <json-schema-editor :value="form.data" disabledType custom />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </EvDrawer>
</template>
<script>
import { data } from 'autoprefixer';

export default {
  props: {
    title: {
      type: String,
      default: "标题",
    },
  },
  data() {
    return {
      microservices: "function-quality",
      resource: "JsonSchemaData",
      dialogVisible: false,
      operate: "add",
      form: {
        name: null,
        data: {
          root: {
            type: "object",
            title: "DTO名称",
            properties: {},
          },
        },
      },
      rules: {
        name: [{ required: true, message: "请输入模型名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入模型编号", trigger: "blur" }],
      },
    };
  },
  created() {

    let form = {
      data: {
        root: {
          type: "object",
          title: "DTO名称",
          properties: {
            calendar: {
              type: 'string',
              title: '日历',
              'x-component': 'Calendar',
              'x-component-props': {
                formItemProps: {
                  placeholder: '选择日历',
                  format: (date) =>
                    date && `${date.getMonth() + 1}/${date.getDate()}`,
                },
                calendarProps: {},
                fieldListeners: {},
                calendarListeners: {},
              },
            },
            cascader: {
              type: 'string',
              title: '地区',
              'x-component': 'Cascader',
              'x-component-props': {
                formItemProps: {
                  placeholder: '请选择所在地区',
                  format: (data) => {
                    const { selectedOptions = [] } = data || {}
                    return selectedOptions.map((option) => option.text).join('/')
                  },
                },
                popupProps: {},
                cascaderProps: {
                  options: [
                    {
                      text: '浙江省',
                      value: '330000',
                      children: [{ text: '杭州市', value: '330100' }],
                    },
                    {
                      text: '江苏省',
                      value: '320000',
                      children: [{ text: '南京市', value: '320100' }],
                    },
                  ],
                },
                fieldListeners: {},
                popupListeners: {},
                cascaderListeners: {
                  change: (...args) => {
                    console.log('onChange args: ', args)
                  },
                },
              },
            },
            code: {
              type: 'string',
              title: '任务编号',
              'x-component': 'Input',
              'x-component-props': { 
                placeholder: '请输入任务编号' 
              },
            },
            title: {
              type:'string',
              title: '任务名称',
              'x-component': 'Input',
              'x-component-props': {
                placeholder: '请输入任务名称'
              },
            },
            level: {
              type:'string',
              title: '优先级',
              'x-component': 'Picker',
              'x-component-props': {
                customShowKey: 'label',
                customValueKey: 'value',
                formItemProps: {
                  placeholder: '请选择优先级',
                },
                popupProps: {},
                pickerProps: {},
                pickerListeners: {}
              },
              enum: [
                { label: '低', value: '3' },
                { label: '中', value: '2' },
                { label: '高', value: '1' },
              ]
            },
            responsibleId: {
              type:'string',
              title: '负责人',
              'x-component': 'Picker',
              'x-component-props': {
                customShowKey: 'name',
                customValueKey: 'value',
                formItemProps: {
                  placeholder: '请选择负责人',
                },
                popupProps: {},
              },
              enum: [],
              'x-reactions': ['{{getPersonList}}'],
              'f-definition':{
                "getPersonList-field": `field.loading = true
                  console.log("getPersonList-field")
                  this.$server()
                    .query("function-user", "User", {}, null, null, false)
                    .then(
                      this.action.bound((data) => {
                        field.dataSource = data.list.map((item) => {
                        return {
                          name: item.name,
                          value: item.id,
                          code: item.code,
                        };
                      })
                        field.loading = false
                      })
                    )
                    .catch((err) => {
                      this.$message.error(err.data.message);
                    });
                `
              }
            },
            planBegin: {
              type: 'string',
              title: '计划开始时间',
              'x-component': 'DatetimePicker',
              'x-component-props': {
                format: 'yyyy-MM-dd HH:mm:ss',
                formItemProps: {
                  placeholder: '请选择计划开始时间',
                },
                datetimePickerProps: {
                  type: 'datetime',
                }
              },
            },
            planEnd: {
              type:'string',
              title: '计划结束时间',
              'x-component': 'DatetimePicker',
              'x-component-props': {
                format: 'yyyy-MM-dd HH:mm:ss',
                formItemProps: {
                  placeholder: '请选择计划结束时间',
                },
                datetimePickerProps: {
                  type: 'datetime',
                },
              },
            },
            workTime: {
              type:'string',
              title: '计划工期',
              'x-component': 'Input',
              'x-component-props': {
                placeholder: '请输入计划工期'
              },
            },
            point: {
              type: 'string',
              title: '生产进度',
              'x-component': 'Input',
              'x-component-props': {
                placeholder: '请输入生产进度'
              },
              'x-content': {
                'right-icon': {
                  render: '{{pointRightRender}}'
                }
              },
              'f-definition':{
                "pointRightRender": `const h = arguments[0];return h("span", ["%"]);`
              }
            },
          },
        },
      }
    }
    let obj = JSON.parse(JSON.stringify(form));

    let jsonString = JSON.stringify(obj.data);

    // 确保 JSON 字符串是 UTF-8 编码的
    const utf8String = new TextEncoder().encode(jsonString);

    // 将 UTF-8 编码的字符串转换为 Base64 编码的字符串
    obj.data = btoa(String.fromCharCode(...new Uint8Array(utf8String)));

    console.log(obj.data);


  },
  methods: {
    open() {
      this.form = {
        name: null,
        data: {
          root: {
            type: "object",
            title: "DTO名称",
            properties: {},
          },
        },
      };
      this.operate = "add";
      this.dialogVisible = true;
    },
    openDetail(id) {
      this.operate = "edit";
      this.$server()
        .getObjectById(this.microservices, this.resource, id)
        .then((res) => {
          console.log(res);
  
          let bytes = Uint8Array.from(atob(res.data), (c) => c.charCodeAt(0));

          let decodedString = new TextDecoder("utf-8").decode(bytes);

          res.data = JSON.parse(decodedString);
          console.log(res.data);
          this.form = res;
        })
        .catch((res) => {
          console.log(res);
          this.$message.error(res.data.message);
        });
      this.dialogVisible = true;
    },
    handleDialogCancel() {
      this.dialogVisible = false;
    },
    handleDialogClose() {
      this.dialogVisible = false;
    },
    handleDialogConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // console.log(this.form);

          // let obj = JSON.parse(JSON.stringify(this.form));
          // obj.data = {
          //   root: this.root,
          // };
          // obj.data = JSON.stringify(obj.data);

          let obj = JSON.parse(JSON.stringify(this.form));

          let jsonString = JSON.stringify(obj.data);

          // 确保 JSON 字符串是 UTF-8 编码的
          const utf8String = new TextEncoder().encode(jsonString);

          // 将 UTF-8 编码的字符串转换为 Base64 编码的字符串
          obj.data = btoa(String.fromCharCode(...new Uint8Array(utf8String)));

          console.log(obj.data);

          // return
          let isUpdate = false;
          if (obj.id && obj.id != "") {
            isUpdate = true;
          }
          this.$server()
            .addOrUpdate(this.microservices, this.resource, obj, isUpdate)
            .then(() => {
              this.$message.success("操作成功");
              this.dialogVisible = false;
              this.$emit("handleDialogConfirm");
            })
            .catch((err) => {
              this.$message.error(err.data.message);
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
